/**
 * 
 */
package vanhoc.android.mediakool.custom.adapter;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vanhoc.android.mediakool.db.DatabaseHelper;
import vanhoc.android.medialcool.item.data.ArtistItemData;
import vanhoc.android.medialcool.item.layout.ArtistItemView;
import vanhoc.android.medialcool.utils.ConnectionDetector;
import vanhoc.android.medialcool.utils.FileUtils;
import vanhoc.android.medialcool.utils.HttpUtils;
import vanhoc.android.medialcool.utils.ImageHelper;
import android.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

/**
 * @author Administrator
 *
 */
public class ArtistGridAdapter extends ArrayAdapter<ArtistItemData> {
	private Context _mContext;
	private static final String  THUMB_FOLDER = Environment.getExternalStorageDirectory().toString()+"/My music/"+"thumb";
	ArrayList<ArtistItemData> _artistItemList;
	//kiem tra xem co ket noi toi internet dc  hay khong
	ConnectionDetector connection;
	HttpUtils httpUtil;
	ImageHelper imgHelper;
	FileUtils fileUtils ;
	ImageHelper imageHelper ;
	static final String ROOT = Environment.getExternalStorageDirectory().toString();
	static final String MYMUSIC = "My music";
	static final String THUMB = "thumb";
	//JSONObject json;
	
	
	public ArtistGridAdapter(Context context, int textViewResourceId,
			List<ArtistItemData> objects) {
		super(context, textViewResourceId, objects);
		// TODO Auto-generated constructor stub
		
		_mContext = context;
		_artistItemList = (ArrayList<ArtistItemData>) objects;
		imgHelper = new ImageHelper(context);
		
		
		fileUtils = new FileUtils();
		connection = new ConnectionDetector(context);
		httpUtil = new HttpUtils();
	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ArtistItemView itemView;
		itemView	=	new ArtistItemView(_mContext);
		
		
		String artistName 		= _artistItemList.get(position).getName();
		String artistThumbnail 	= _artistItemList.get(position).getThumbPath();
		Log.e("artistThumbnail", ""+artistThumbnail.toString());
		
		
		//display artist name
		itemView.artistName.setText(artistName);
		
		if (artistThumbnail.equals("") || artistThumbnail.equals(null)) { 
			//Tao thu muc luu avatar
			createStoreThumbDirectory();
			
			//search, download-store ....
			String imgUrl = searchArtistThumbUrl(artistName);
			Log.e("imgUrl", ""+imgUrl);
			String storePath = ROOT+"/"+MYMUSIC+"/"+THUMB;
			if (downloadArtistThumbnail(imgUrl,artistName,THUMB_FOLDER)) {
				//luu vao csdl
				String thumbPath = storePath+"/"+artistName+".jpg";
				updateArtistThumbPath(artistName, thumbPath);
				
				
				Bitmap bm = BitmapFactory.decodeFile(storePath+"/"+artistName+".jpg"); //vd thoi
				if (bm != null) {
					itemView.artistThumb.setImageBitmap(bm);
				}else{
					itemView.artistThumb.setImageResource(vanhoc.android.mediakool.R.drawable.dvd_120_icon);
				}
			}else{
				itemView.artistThumb.setImageResource(vanhoc.android.mediakool.R.drawable.dvd_120_icon);
			}
			
			
			/*if (connection.isConnectingToInternet()) {//----Neu co ket noi internet thi search,tai va luu vao thu muc /mnt/sdcard/My music/thumb/
				//search, download-store ....
				//storeArtistThumbnail();
				Log.e("internetConnection", "co mang");
			}else{//----//Neu khong co mang, khong ket noi dc toi internet thi dat icon mac dinh len
				//setArtistDataListDefault();
				Log.e("internetConnection", "co mang");
			}*/
			
			
		}else{//co duong dan hinh toi file anh
			//th1 : co duong dan toi file hinh va file hinh co ton tai -> tao dc bit map
			//th2 : co duong dan toi file hinh va file hinh kong ton tai -> khong tao dc bit map ->dat icon mac dinh
			Bitmap bm = BitmapFactory.decodeFile(artistThumbnail);
			if (bm != null) {
				itemView.artistThumb.setImageBitmap(bm);
			}else{
				itemView.artistThumb.setImageResource(vanhoc.android.mediakool.R.drawable.dvd_120_icon);
			}
		}
		return itemView;
	}


	private void updateArtistThumbPath(String artistName, String thumbPath) {
		DatabaseHelper db = new DatabaseHelper(this._mContext);
		db.openToWrite();
		db.updateArtistThumbnailPath(artistName, thumbPath);
		db.close();
	}


	private void createStoreThumbDirectory() {
		String musicPath = ROOT + "/" + MYMUSIC;
		String thumbPath = musicPath+"/"+THUMB;
		if (!fileUtils.isExist(musicPath)) { //neu chua co thu muc My music
			if (fileUtils.createNewDirectory(musicPath)) { //tao thanh cong
				if (!fileUtils.isExist(thumbPath)) { // neu trong co thu muc thumb
					if (fileUtils.createNewDirectory(thumbPath)) { // tao thanh cong
						Log.e("Tao thumb path ", "Thanh cong");
					}else{
						Log.e("Tao thumb path ", "khong thanh cong");
					}
				}
			}
		}else{//neu co thu muc My music roi
			if (!fileUtils.isExist(thumbPath)) { // neu trong co thu muc thumb
				if (fileUtils.createNewDirectory(thumbPath)) { // tao thanh cong
					Log.e("Tao thumb path ", "Thanh cong");
				}else{
					Log.e("Tao thumb path ", "khong thanh cong");
				}
			}
		}
	}
	
	
	
	public String searchArtistThumbUrl(String artistName) {
		String imgUrl = null;
		URL url;
		//url
		try {
			   url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
			   	"v=1.0&q="+Uri.encode(artistName)+"&rsz=1"); //&key=ABQIAAAADxhJjHRvoeM2WF3nxP5rCBRcGWwHZ9XQzXD3SWg04vbBlJ3EWxR0b0NVPhZ4xmhQVm3uUBvvRF-VAA&userip=192.168.0.172");
		   
			   URLConnection connection = url.openConnection();
			   connection.addRequestProperty("Referer", "http://technotalkative.com");
			   
			   String line;
			   StringBuilder builder = new StringBuilder();
			   BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			   while((line = reader.readLine()) != null) {
				   builder.append(line);
			   }

			   JSONObject json = new JSONObject(builder.toString());
			   imgUrl = getUrl(json);
		   } catch (MalformedURLException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return imgUrl;
	}
	
	
	/**
	 * @param json 
	 * 
	 */
	public String getUrl(JSONObject json){
		String url = null;
		try {
		   	JSONObject responseObject = json.getJSONObject("responseData");
		   	JSONArray resultArray = responseObject.getJSONArray("results");
		   	try 
			{
				for(int i=0; i<resultArray.length(); i++){
					JSONObject obj;
					obj = resultArray.getJSONObject(i);
					url = obj.getString("tbUrl");
					//url = obj.getString("url");
				} 
			 }
			 catch (JSONException e) 
			 {
				e.printStackTrace();
			 }
	   } catch (JSONException e) {
		   e.printStackTrace();
	   }
	
		return url;
	}
	
	
	
	
	
	/**
	 * 
	 * @param imgUrl : url cua hinh
	 * @param artistName : ten muon dat cho cai hinh khi tai ve
	 * @param thumbFolder : thu muc luu hinh
	 */
	public Boolean downloadArtistThumbnail(String imgUrl, String artistName, String thumbFolder){
		try {
			InputStream is = httpUtil.OpenHttpConnection(imgUrl);
			Bitmap bm = imgHelper.getBitMap(is);
			if (imgHelper.storeImage(thumbFolder, artistName+".jpg", bm)) {
				return true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
